package org.jeecg.modules.wmhb.service.impl;

import org.apache.commons.lang.StringUtils;
import org.jeecg.modules.wmhb.entity.WmTaskbookFlow;
import org.jeecg.modules.wmhb.entity.WmFlowDept;
import org.jeecg.modules.wmhb.mapper.WmFlowDeptMapper;
import org.jeecg.modules.wmhb.mapper.WmTaskbookFlowMapper;
import org.jeecg.modules.wmhb.service.IWmTaskbookFlowService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 任务书流程表
 * @Author: jeecg-boot
 * @Date:   2024-09-05
 * @Version: V1.0
 */
@Service
public class WmTaskbookFlowServiceImpl extends ServiceImpl<WmTaskbookFlowMapper, WmTaskbookFlow> implements IWmTaskbookFlowService {

	@Autowired
	private WmTaskbookFlowMapper wmTaskbookFlowMapper;
	@Autowired
	private WmFlowDeptMapper wmFlowDeptMapper;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(WmTaskbookFlow wmTaskbookFlow, List<WmFlowDept> wmFlowDeptList) {
		wmTaskbookFlowMapper.insert(wmTaskbookFlow);
		if(wmFlowDeptList!=null && wmFlowDeptList.size()>0) {
			for(WmFlowDept entity:wmFlowDeptList) {
				//外键设置
				entity.setWmTaskbookFlowId(wmTaskbookFlow.getId());
				if(StringUtils.isEmpty(entity.getDeptId())){
					throw new RuntimeException("部门ID不能为空");
				}
				wmFlowDeptMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(WmTaskbookFlow wmTaskbookFlow,List<WmFlowDept> wmFlowDeptList) {
		wmTaskbookFlowMapper.updateById(wmTaskbookFlow);
		
		//1.先删除子表数据
		wmFlowDeptMapper.deleteByMainId(wmTaskbookFlow.getId());
		
		//2.子表数据重新插入
		if(wmFlowDeptList!=null && wmFlowDeptList.size()>0) {
			for(WmFlowDept entity:wmFlowDeptList) {
				//外键设置
				entity.setWmTaskbookFlowId(wmTaskbookFlow.getId());
				if(StringUtils.isEmpty(entity.getDeptId())){
					throw new RuntimeException("部门ID不能为空");
				}
				wmFlowDeptMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		wmFlowDeptMapper.deleteByMainId(id);
		wmTaskbookFlowMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			wmFlowDeptMapper.deleteByMainId(id.toString());
			wmTaskbookFlowMapper.deleteById(id);
		}
	}

	@Override
	public List<String> selectBuDepart(String buId){
		List<WmFlowDept> wmFlowDeptList = baseMapper.selectBuDepart(buId);
		List<String> idList = new ArrayList<>();
		for(WmFlowDept wmFlowDept: wmFlowDeptList){
			idList.add(wmFlowDept.getDeptId());
		}
		return idList;
	}
	
}
